"""
图像质量检测演示脚本

用于验证改进后的质量检测算法对黑白扫描件的处理效果
"""

import cv2
import numpy as np
from PIL import Image
import sys
import os

# 添加项目根目录到路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from src.services.quality.quality_checker import QualityChecker


def create_test_images():
    """创建测试图像"""
    
    # 1. 创建黑白扫描文档(文字密集)
    print("创建测试图像...")
    
    # 创建一个模拟的黑白扫描文档
    width, height = 1200, 1600
    img = np.ones((height, width), dtype=np.uint8) * 250  # 白色背景
    
    # 添加文字(黑色矩形模拟)
    for i in range(50):  # 50行文字
        y = 100 + i * 30
        # 每行10-15个"字"(小黑块)
        for j in range(np.random.randint(10, 15)):
            x = 100 + j * 80 + np.random.randint(-10, 10)
            char_width = np.random.randint(15, 25)
            char_height = np.random.randint(20, 25)
            # 文字灰度值在10-40之间
            gray_value = np.random.randint(10, 40)
            img[y:y+char_height, x:x+char_width] = gray_value
    
    # 添加表格线
    for i in range(5):
        y = 300 + i * 200
        cv2.line(img, (100, y), (1100, y), 20, 2)
    
    for i in range(10):
        x = 100 + i * 100
        cv2.line(img, (x, 300), (x, 1100), 20, 2)
    
    # 添加印章(模拟,椭圆形黑色)
    cv2.ellipse(img, (900, 1400), (60, 80), 0, 0, 360, 15, -1)
    
    return img


def test_quality_detection():
    """测试质量检测"""
    
    print("\n" + "="*80)
    print("图像质量检测演示 - 黑白扫描文档")
    print("="*80 + "\n")
    
    # 创建测试图像
    test_img = create_test_images()
    
    print(f"测试图像信息:")
    print(f"  尺寸: {test_img.shape[1]}x{test_img.shape[0]}")
    print(f"  类型: 黑白扫描文档(模拟)")
    print(f"  内容: 文字密集,包含表格和印章")
    print()
    
    # 运行质量检测
    try:
        result = QualityChecker.check_image_quality(test_img, trace_id="demo_test")
        
        print("="*80)
        print("检测结果:")
        print("="*80)
        print()
        
        # 综合评估
        print(f"🎯 综合评估: {result['overall_status'].upper()}")
        print(f"📝 消息: {result['message']}")
        print()
        
        # 清晰度
        clarity = result['clarity']
        print(f"1️⃣  清晰度检测:")
        print(f"    状态: {clarity['status']}")
        print(f"    分数: {clarity['score']:.2f}/100")
        print(f"    等级: {clarity['level']}")
        print(f"    详细指标:")
        print(f"      - Laplacian方差: {clarity['details']['laplacian_variance']:.2f}")
        print(f"      - Tenengrad梯度: {clarity['details']['tenengrad']:.2f}")
        print(f"      - 方差系数: {clarity['details']['variance_coefficient']:.2f}%")
        print(f"    归一化分数:")
        for key, val in clarity['details']['normalized_scores'].items():
            print(f"      - {key}: {val:.2f}/100")
        print()
        
        # 分辨率
        resolution = result['resolution']
        print(f"2️⃣  分辨率检测:")
        print(f"    状态: {resolution['status']}")
        print(f"    分辨率: {resolution['resolution']}")
        print(f"    等级: {resolution['level']}")
        print(f"    最低要求: {resolution['min_required']}")
        print()
        
        # 遮挡
        occlusion = result['occlusion']
        print(f"3️⃣  遮挡检测:")
        print(f"    状态: {occlusion['status']}")
        print(f"    黑色区域占比: {occlusion['black_ratio']:.4f} ({occlusion['black_ratio']*100:.2f}%)")
        print(f"    噪点占比: {occlusion['noise_ratio']:.4f} ({occlusion['noise_ratio']*100:.2f}%)")
        print(f"    大面积遮挡: {len(occlusion['large_occlusions'])} 个")
        if occlusion['issues']:
            print(f"    问题: {', '.join(occlusion['issues'])}")
        print()
        
        # 详细信息
        print(f"📊 详细统计:")
        detail = occlusion['detail']
        print(f"    总像素: {detail['total_pixels']:,}")
        print(f"    黑色像素: {detail['black_pixels']:,}")
        print(f"    噪点像素: {detail['noise_pixels']:,}")
        if detail['serious_issues']:
            print(f"    严重问题: {detail['serious_issues']}")
        if detail['warnings']:
            print(f"    警告: {detail['warnings']}")
        print()
        
        print("="*80)
        print("✅ 检测完成!")
        print("="*80)
        
        # 保存测试图像(如果需要)
        output_path = "test_scan_document.png"
        cv2.imwrite(output_path, test_img)
        print(f"\n💾 测试图像已保存到: {output_path}")
        
        return result
        
    except Exception as e:
        print(f"❌ 检测失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return None


def test_image_type_detection():
    """测试图像类型识别"""
    
    print("\n" + "="*80)
    print("图像类型识别测试")
    print("="*80 + "\n")
    
    # 测试1: 黑白扫描件
    img_binary = np.ones((1000, 1000), dtype=np.uint8) * 250
    for i in range(100):
        y = np.random.randint(50, 950)
        x = np.random.randint(50, 950)
        img_binary[y:y+20, x:x+15] = np.random.randint(5, 30)
    
    img_type = QualityChecker._detect_image_type(img_binary, "test1")
    print(f"测试1 - 黑白扫描文档: {img_type}")
    assert img_type == 'binary_scan', f"识别错误,期望binary_scan,实际{img_type}"
    print("  ✅ 通过")
    
    # 测试2: 灰度图像
    img_gray = np.random.randint(50, 200, (1000, 1000), dtype=np.uint8)
    img_type = QualityChecker._detect_image_type(img_gray, "test2")
    print(f"\n测试2 - 灰度图像: {img_type}")
    assert img_type == 'grayscale', f"识别错误,期望grayscale,实际{img_type}"
    print("  ✅ 通过")
    
    # 测试3: 彩色图像
    img_color = np.random.randint(0, 255, (1000, 1000, 3), dtype=np.uint8)
    img_type = QualityChecker._detect_image_type(img_color, "test3")
    print(f"\n测试3 - 彩色图像: {img_type}")
    assert img_type == 'color', f"识别错误,期望color,实际{img_type}"
    print("  ✅ 通过")
    
    print("\n" + "="*80)
    print("✅ 所有类型识别测试通过!")
    print("="*80)


if __name__ == "__main__":
    print("\n🚀 启动图像质量检测演示\n")
    
    # 测试1: 类型识别
    test_image_type_detection()
    
    # 测试2: 质量检测
    result = test_quality_detection()
    
    if result:
        print("\n🎉 演示完成!请检查以上结果,验证:")
        print("  1. 黑白扫描文档是否被正确识别")
        print("  2. 文字密集文档是否没有被误判为'遮挡'")
        print("  3. 印章是否没有触发'黑色区域过多'警告")
        print("  4. 整体评估是否为'passed'或'warning'(而非'failed')")
    else:
        print("\n❌ 演示失败,请检查错误信息")

